<template>
  <div class="page-container">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/reports">汇报材料</el-breadcrumb-item>
        <el-breadcrumb-item>心得体会</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="header-title">
        <h1>
          <el-icon class="title-icon"><Notebook /></el-icon>
          心得体会生成
        </h1>
        <p class="subtitle">专业的心得体会生成工具，规范流程，高质量输出</p>
      </div>
      
      <!-- 进度指示器 -->
      <div class="steps-container">
        <el-steps :active="currentStep" align-center>
          <el-step title="基础信息" icon="EditPen" />
          <el-step title="更多信息" icon="InfoFilled" />
          <el-step title="生成心得" icon="DocumentChecked" />
        </el-steps>
      </div>
    </div>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1: 基础信息 -->
      <div v-show="currentStep === 0" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><EditPen /></el-icon>
              <span>基础信息</span>
            </div>
          </template>
          
          <el-form 
            :model="formData" 
            :rules="basicRules" 
            ref="basicFormRef" 
            label-width="120px"
            class="step-form"
          >
            <!-- 文稿类型 -->
            <el-form-item label="文稿类型" prop="experienceType" required>
              <div class="radio-grid">
                <el-radio-group v-model="formData.experienceType">
                  <el-radio value="study" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">学习心得</div>
                      <div class="radio-desc">理论学习感悟</div>
                    </div>
                  </el-radio>
                  <el-radio value="practice" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">实践感悟</div>
                      <div class="radio-desc">实际工作体会</div>
                    </div>
                  </el-radio>
                  <el-radio value="media" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">观影/读书体会</div>
                      <div class="radio-desc">文化学习感受</div>
                    </div>
                  </el-radio>
                  <el-radio value="custom" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">自定义</div>
                      <div class="radio-desc">其他类型体会</div>
                    </div>
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>

            <!-- 主题 -->
            <el-form-item label="主题" prop="theme" required>
              <el-input
                v-model="formData.theme"
                placeholder="请输入主题"
                maxlength="200"
                show-word-limit
                class="theme-input"
              />
            </el-form-item>

            <!-- 内容 -->
            <el-form-item label="内容" prop="content" required>
              <el-input
                v-model="formData.content"
                type="textarea"
                :rows="6"
                placeholder="请输入内容"
                maxlength="3000"
                show-word-limit
                class="content-textarea"
              />
            </el-form-item>

            <!-- 篇幅 -->
            <el-form-item label="篇幅" prop="wordCount" required>
              <div class="word-count-container">
                <el-radio-group v-model="formData.wordCount" class="word-count-group">
                  <el-radio value="1500">1500字左右</el-radio>
                  <el-radio value="2000">2000字左右</el-radio>
                  <el-radio value="2500">2500字左右</el-radio>
                  <el-radio value="custom">自定义</el-radio>
                </el-radio-group>
                <el-input-number
                  v-if="formData.wordCount === 'custom'"
                  v-model="formData.customWordCount"
                  :min="500"
                  :max="10000"
                  :step="100"
                  placeholder="请输入字数"
                  class="custom-word-input"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤2: 更多信息 -->
      <div v-show="currentStep === 1" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>更多信息</span>
            </div>
          </template>
          
          <el-form 
            :model="formData" 
            :rules="additionalRules" 
            ref="additionalFormRef" 
            label-width="120px"
            class="step-form"
          >
            <!-- 感悟内容 -->
            <el-form-item label="感悟内容">
              <el-input
                v-model="formData.insight"
                type="textarea"
                :rows="4"
                placeholder="请输入感悟内容"
                maxlength="200"
                show-word-limit
                class="insight-textarea"
              />
            </el-form-item>

            <!-- 受众提示 -->
            <el-form-item label="受众提示">
              <div class="radio-grid">
                <el-radio-group v-model="formData.audience">
                  <el-radio value="leader" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">供领导审阅</div>
                      <div class="radio-desc">正式严谨风格</div>
                    </div>
                  </el-radio>
                  <el-radio value="colleague" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">面向同事分享</div>
                      <div class="radio-desc">交流分享风格</div>
                    </div>
                  </el-radio>
                  <el-radio value="public" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">公开网络发布</div>
                      <div class="radio-desc">通俗易懂风格</div>
                    </div>
                  </el-radio>
                  <el-radio value="custom" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">自定义</div>
                      <div class="radio-desc">其他受众</div>
                    </div>
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>

            <!-- 其他写作信息 -->
            <el-form-item label="其他写作信息">
              <el-input
                v-model="formData.otherInfo"
                type="textarea"
                :rows="4"
                placeholder="请输入其他写作信息"
                maxlength="3000"
                show-word-limit
                class="other-info-textarea"
              />
            </el-form-item>

            <!-- 参考文档 -->
            <el-form-item label="参考文档">
              <el-upload
                v-model:file-list="formData.referenceFiles"
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :before-remove="handleFileRemove"
                :accept="'.doc,.docx,.xls,.xlsx'"
                multiple
                class="upload-demo"
              >
                <el-button type="primary" plain>
                  <el-icon><Upload /></el-icon>
                  上传文件
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持word、excel文件，文件2mb以内，最多一万字
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤3: 生成结果 -->
      <div v-show="currentStep === 2" class="step-panel">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon><DocumentChecked /></el-icon>
                <span>生成结果</span>
              </div>
              <div class="header-actions" v-if="generatedContent">
                <el-button type="text" @click="copyContent" :icon="DocumentCopy">
                  复制
                </el-button>
                <el-button type="text" @click="exportContent" :icon="Download">
                  导出
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 生成中状态 -->
          <div v-if="isGenerating" class="generating-content">
            <div class="generating-animation">
              <el-icon class="rotating"><Loading /></el-icon>
              <p>正在生成心得体会，请稍候...</p>
            </div>
          </div>

          <!-- 生成结果 -->
          <div v-else-if="generatedContent" class="result-content">
            <div class="result-stats">
              <el-tag type="info">字数: {{ contentStats.wordCount }}</el-tag>
              <el-tag type="success">段落: {{ contentStats.paragraphs }}</el-tag>
              <el-tag type="warning">用时: {{ generationTime }}ms</el-tag>
              <el-tag v-if="generationCost" type="danger">成本: ¥{{ generationCost.toFixed(4) }}</el-tag>
            </div>
            
            <div class="content-display">
              <div class="content-text" v-html="formattedContent"></div>
            </div>
          </div>

          <!-- 未生成状态 -->
          <div v-else class="empty-content">
            <el-empty description="点击下方按钮开始生成心得体会">
              <template #image>
                <el-icon size="80" color="#ddd"><DocumentChecked /></el-icon>
              </template>
            </el-empty>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="step-actions">
      <el-button 
        v-if="currentStep > 0" 
        @click="prevStep"
        size="large"
      >
        上一步
      </el-button>
      
      <el-button 
        v-if="currentStep < 2"
        type="danger" 
        @click="nextStep"
        size="large"
        :loading="isValidating"
      >
        下一步
      </el-button>
      
      <el-button 
        v-if="currentStep === 2"
        type="danger" 
        size="large"
        @click="generateContent"
        :loading="isGenerating"
        :disabled="!canGenerate"
      >
        <el-icon><Magic /></el-icon>
        生成心得
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { DocumentCopy, Download } from '@element-plus/icons-vue'
import { useModelConfigStore } from '@/stores/modelConfig'
import { aiService } from '@/services/aiService'
import type { UploadFile, FormInstance } from 'element-plus'

// 表单数据接口
interface ExperienceForm {
  // 基础信息
  experienceType: string
  theme: string
  content: string
  wordCount: string
  customWordCount?: number
  
  // 更多信息
  insight: string
  audience: string
  otherInfo: string
  referenceFiles: UploadFile[]
}

// 响应式数据
const currentStep = ref(0)
const isValidating = ref(false)
const isGenerating = ref(false)
const generatedContent = ref('')
const generationTime = ref(0)
const generationCost = ref(0)

// 表单引用
const basicFormRef = ref<FormInstance>()
const additionalFormRef = ref<FormInstance>()

// 表单数据
const formData = reactive<ExperienceForm>({
  // 基础信息
  experienceType: '',
  theme: '',
  content: '',
  wordCount: '2000',
  customWordCount: 2000,
  
  // 更多信息
  insight: '',
  audience: 'leader',
  otherInfo: '',
  referenceFiles: []
})

// 验证规则
const basicRules = {
  experienceType: [
    { required: true, message: '请选择文稿类型', trigger: 'change' }
  ],
  theme: [
    { required: true, message: '请输入主题', trigger: 'blur' },
    { min: 2, max: 200, message: '主题长度应在2-200字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 3000, message: '内容长度应在10-3000字符之间', trigger: 'blur' }
  ],
  wordCount: [
    { required: true, message: '请选择篇幅', trigger: 'change' }
  ]
}

const additionalRules = {
  // 更多信息字段都是可选的，暂不设置必填规则
}

// 计算属性
const canGenerate = computed(() => {
  return formData.experienceType && formData.theme && formData.content
})

const contentStats = computed(() => {
  if (!generatedContent.value) {
    return { wordCount: 0, paragraphs: 0 }
  }
  
  const text = generatedContent.value.replace(/<[^>]*>/g, '')
  const wordCount = text.length
  const paragraphs = text.split('\n\n').filter(p => p.trim()).length
  
  return { wordCount, paragraphs }
})

const formattedContent = computed(() => {
  return generatedContent.value.replace(/\n/g, '<br>')
})

// 方法
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 验证基础信息
    if (!basicFormRef.value) return
    
    isValidating.value = true
    try {
      await basicFormRef.value.validate()
      currentStep.value++
    } catch {
      ElMessage.error('请完善基础信息')
    } finally {
      isValidating.value = false
    }
  } else if (currentStep.value === 1) {
    // 更多信息步骤无必填项，直接进入下一步
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const generateContent = async () => {
  const modelStore = useModelConfigStore()
  const currentProvider = modelStore.getCurrentProvider()
  
  if (!currentProvider?.hasApiKey) {
    ElMessage.error('请先配置AI模型的API密钥')
    return
  }

  isGenerating.value = true

  try {
    // 构建系统提示词
    const systemPrompt = buildSystemPrompt()
    
    // 构建用户提示词
    const userPrompt = buildUserPrompt()

    const response = await aiService.generateText({
      systemPrompt,
      userPrompt
    })

    generatedContent.value = response.content
    generationTime.value = response.duration
    generationCost.value = response.cost || 0

    ElNotification({
      title: '生成成功',
      message: `心得体会已生成完成，用时 ${response.duration}ms`,
      type: 'success',
      duration: 3000
    })

  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '生成失败，请重试')
  } finally {
    isGenerating.value = false
  }
}

const buildSystemPrompt = (): string => {
  const typeMap = {
    study: '学习心得',
    practice: '实践感悟', 
    media: '观影/读书体会',
    custom: '自定义类型体会'
  }

  const audienceMap = {
    leader: '供领导审阅（正式严谨风格）',
    colleague: '面向同事分享（交流分享风格）',
    public: '公开网络发布（通俗易懂风格）',
    custom: '自定义受众'
  }

  const wordCount = formData.wordCount === 'custom' ? formData.customWordCount : parseInt(formData.wordCount)

  return `你是一位专业的公务员写作助手，专门负责撰写高质量的心得体会。请根据以下要求生成一份专业的${typeMap[formData.experienceType as keyof typeof typeMap]}：

写作要求：
1. 文稿类型：${typeMap[formData.experienceType as keyof typeof typeMap]}
2. 受众对象：${audienceMap[formData.audience as keyof typeof audienceMap]}
3. 目标字数：约${wordCount}字
4. 写作风格：根据受众调整语言风格和表达方式

写作特点：
- 语言真挚感人，体现个人真实感悟
- 逻辑清晰，层次分明
- 理论联系实际，有深度有内涵
- 格式规范，便于阅读

请确保内容真实可信，避免空洞的套话，注重个人感悟和思考的展示。`
}

const buildUserPrompt = (): string => {
  let prompt = `请根据以下信息生成心得体会：

主题：${formData.theme}
内容要点：${formData.content}`

  if (formData.insight) {
    prompt += `\n\n感悟内容：${formData.insight}`
  }

  if (formData.otherInfo) {
    prompt += `\n\n其他写作信息：${formData.otherInfo}`
  }

  if (formData.referenceFiles.length > 0) {
    prompt += `\n\n参考文档：${formData.referenceFiles.map(file => file.name).join('、')}`
  }

  return prompt
}

const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(generatedContent.value)
    ElMessage.success('内容已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}

const exportContent = () => {
  const blob = new Blob([generatedContent.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `心得体会_${formData.theme}_${new Date().toLocaleDateString()}.txt`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  ElMessage.success('文件已导出')
}

const handleFileChange = (file: UploadFile) => {
  // 检查文件大小（2MB限制）
  if (file.raw && file.raw.size > 2 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过2MB')
    // 从文件列表中移除
    const index = formData.referenceFiles.findIndex(f => f.uid === file.uid)
    if (index > -1) {
      formData.referenceFiles.splice(index, 1)
    }
    return false
  }
  return true
}

const handleFileRemove = () => {
  return true
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 30px;
}

.header-title {
  margin-top: 16px;
  text-align: center;
}

.header-title h1 {
  color: #dc3545;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 600;
}

.title-icon {
  font-size: 32px;
}

.subtitle {
  color: #666;
  margin: 12px 0 0 0;
  font-size: 16px;
}

.steps-container {
  margin-top: 30px;
  padding: 0 20px;
}

.step-content {
  margin: 30px 0;
  min-height: 500px;
}

.step-panel {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.step-card, .result-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 12px;
  min-height: 400px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.step-form {
  padding: 20px;
}

/* 单选框网格布局 */
.radio-grid {
  width: 100%;
}

.radio-grid .el-radio-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  width: 100%;
}

.radio-card {
  display: flex !important;
  align-items: flex-start;
  padding: 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
  background: #fafafa;
  margin: 0 !important;
  height: auto;
  min-height: 70px;
}

.radio-card:hover {
  border-color: #dc3545;
  background: #fff5f5;
}

.radio-card.is-checked {
  border-color: #dc3545;
  background: #fff5f5;
}

.radio-content {
  margin-left: 8px;
  flex: 1;
}

.radio-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.radio-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 篇幅选择样式 */
.word-count-container {
  width: 100%;
}

.word-count-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.word-count-group .el-radio {
  margin-right: 0;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.word-count-group .el-radio:hover {
  border-color: #dc3545;
  background: #fff5f5;
}

.word-count-group .el-radio.is-checked {
  border-color: #dc3545;
  background: #fff5f5;
}

.custom-word-input {
  width: 200px;
}

.theme-input,
.content-textarea,
.insight-textarea,
.other-info-textarea {
  width: 100%;
}

.upload-demo {
  width: 100%;
}

.generating-content {
  padding: 80px 20px;
  text-align: center;
}

.generating-animation {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.rotating {
  font-size: 48px;
  color: #dc3545;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.result-content {
  padding: 20px;
}

.result-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.content-display {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
  min-height: 300px;
}

.content-text {
  line-height: 1.8;
  font-size: 14px;
  color: #303133;
  white-space: pre-line;
}

.empty-content {
  padding: 80px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: white;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.step-actions .el-button {
  min-width: 120px;
  padding: 12px 30px;
  font-size: 16px;
}

/* Element Plus Steps 自定义样式 */
:deep(.el-steps) {
  margin: 0 auto;
  max-width: 600px;
}

:deep(.el-step__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-step__title.is-process) {
  color: #dc3545;
  font-weight: 600;
}

:deep(.el-step__icon.is-process) {
  color: #dc3545;
  border-color: #dc3545;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #dc3545;
  background: #dc3545;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #dc3545;
  border-color: #dc3545;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 15px;
  }
  
  .header-title h1 {
    font-size: 24px;
    flex-direction: column;
    gap: 8px;
  }
  
  .radio-grid .el-radio-group {
    grid-template-columns: 1fr;
  }
  
  .word-count-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .word-count-group .el-radio {
    width: 100%;
    justify-content: center;
  }
  
  .custom-word-input {
    width: 100%;
  }
  
  .step-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .step-actions .el-button {
    width: 100%;
    max-width: 300px;
  }
}
</style>